--[[
登录界面
2015_12_03 C.P
功能：登录/注册
--]]

appdf.BASE_SRC                              = ""
appdf.CLIENT_SRC                            = ""
	--扩展目录
appdf.EXTERNAL_SRC							= "external."
	--通用定义目录
appdf.HEADER_SRC							= "header."

package.loaded[appdf.EXTERNAL_SRC .. "ExternalFun"] = nil
appdf.req(appdf.EXTERNAL_SRC .. "Logon_ExternalFun")

local config_path = appdf.req("config_path")
local EXTRA_CMD_KEY = "extra_command_version"
local pack = package.loaded
	
if not yl then
	appdf.req(appdf.CLIENT_SRC.."plaza.models.yl")
end
if not GlobalUserItem then
	appdf.req(appdf.CLIENT_SRC.."plaza.models.GlobalUserItem")
	appdf.req(appdf.CLIENT_SRC .."app.views.layer.other.Toast")
end
local utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")
local SDKUtils = appdf.req(appdf.EXTERNAL_SRC .. "SDKUtils")
local MultiPlatform = appdf.req(appdf.EXTERNAL_SRC .. "MultiPlatform")
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
local privatemgr = ""

local LogonScene = class("LogonScene", cc.load("mvc").ViewBase)
	local BaseFrame = appdf.req(appdf.CLIENT_SRC.."plaza.models.BaseFrame")
local PopWait = appdf.req(appdf.CLIENT_SRC.."app.views.layer.other.PopWait")
local QueryExit = appdf.req(appdf.CLIENT_SRC.."app.views.layer.other.QueryDialog")

local LogonFrame = appdf.req(appdf.CLIENT_SRC.."plaza.models.LogonFrame")
local LogonView = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.logon.LogonView")


local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
local protocol = require("gamemodel.protocol")

LogonScene.BT_EXIT 			= 1
LogonScene.DG_QUERYEXIT 	= 2
appdf.MachineCode = MultiPlatform:getInstance():getMachineId()

--全局处理lua错误
cc.exports.g_LuaErrorHandle = function ()
	cc.exports.bHandlePopErrorMsg = true
	if isDebug() then
		local MultiPlatform = appdf.req(appdf.EXTERNAL_SRC .. "MultiPlatform")	print("debug return")
		return true
	else
		print("release return")
		return false
	end
end
 


local FIRST_LOGIN = true
-- 进入场景而且过渡动画结束时候触发。
-- function LogonScene:onEnterTransitionFinish()
-- 	self:releasePublicRes()
-- 	self:initView()
-- 	return self
-- end

function LogonScene:releasePublicRes()
	ExternalFun:removeArmatureCache()
end

-- 退出场景而且开始过渡动画时候触发。
function LogonScene:onExitTransitionStart()
	self._backLayer:unregisterScriptKeypadHandler()
	self._backLayer:setKeyboardEnabled(false)
	return self
end

function LogonScene:initSocketEvent( ... )

	if not appdf.ip or trim(appdf.ip) == "" then
		appdf.ip = "0.0.0.0"  -- 获取不到ip  默认值
	end

	if  not appdf.clientSocket then
		
		local logonCallBack = function (result,message)
			-- print("onLogonCallBack>>>>>>",result,message)
			if self.onLogonCallBack then
				self:onLogonCallBack(result,message)
			end
		end
		
	
		appdf.clientSocket = BaseFrame:create(self,logonCallBack)
		self:showPopWait()
		self._logonView:showLoninViewBtn(true)
		local  cfgdata = self:getApp()._serverConfig or {}
	
		appdf.clientSocket:connectServer()
		-- self._logonView:showLoninViewBtn(false)

	else
		print("logout>>>>>>>>>>>")
		appdf.clientSocket:logout()
		appdf.clientSocket:onCloseSocket()
		GlobalUserItem.dwUserID = ""
		self._logonView:showLoninViewBtn(true)

	end
	appdf.clientSocket:setViewFrame(self)
	local logonCallBack = function (result,message)
		-- print("onLogonCallBack>>>>>>",result,message)
		if self.onLogonCallBack then
			self:onLogonCallBack(result,message)
		end
	end
	local _logonFrame = LogonFrame:create(self,logonCallBack)
	self._logonFrame = _logonFrame
	
	appdf.clientSocket.onSocketLoginEvent  =  function ( self,wMsgID,recvJson )
		_logonFrame:onSocketEvent(wMsgID,recvJson)
	end

	
end

function LogonScene:initHttpUrl( ... )
	
	local  cfgdata = self:getApp()._serverConfig
	appdf.isDebug = cfgdata.debug or device.platform == "windows"
	

	appdf.addbasepath =  appdf.addbasepath or "base/"

	appdf.CLIENT_RES = "client/res/"

	appdf.GAME_SRC = "download."
	appdf.gamepath =  device.writablePath.."/download/"
	appdf.gamecodepath =  "download."

	
	
	if appdf.isDebug  or appdf.APPSTORE_VERSION then  ---是否使用本地路径
		appdf.GAME_SRC = "game."
		appdf.gamepath =  "game/"
		appdf.gamecodepath =  "game."
	end

	
end

-- 初始化界面
function LogonScene:onCreate()
	print("LogonScene:onCreate>><<<")
	-- self:releasePublicRes()
	self:initView()
	appdf.inClientScene =  false

	local  cfgdata = self:getApp()._serverConfig or {}
	URL_REQUEST_LIST = cfgdata.confighostList or URL_REQUEST_LIST
	URL_REQUEST = URL_REQUEST_LIST[1]

end

-- 初始化界面
function LogonScene:initView()


	local this = self
	self.retryTime = 1
	
	
	self:registerScriptHandler(function (eventType)
		if eventType == "enterTransitionFinish" then	-- 进入场景而且过渡动画结束时候触发。
			this:onEnterTransitionFinish()
		elseif eventType == "exitTransitionStart" then	-- 退出场景而且开始过渡动画时候触发。
			this:onExitTransitionStart()
		end
	end)
	
	local  btcallback = function (ref, type)
		if type == ccui.TouchEventType.ended then
			this:onButtonClickedEvent(ref:getTag(),ref)
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
	end
	
	self._backLayer = display.newLayer()
	:setContentSize(1334,750)
	:addTo(self)
	
	--返回键事件
	self._backLayer:registerScriptKeypadHandler(function (event)
		if event == "backClicked" then
			if this._popWait == nit then
				this:onButtonClickedEvent(LogonScene.BT_EXIT)
			end
		end
	end)
	self._backLayer:setKeyboardEnabled(true)
	
	self._topLayer = display.newLayer()
	:addTo(self)

	
	--返回
	if  device.platform ~= "mac" and device.platform ~= "ios" then
		ccui.Button:create("bt_return_0.png","bt_return_1.png")
		:move(75,yl.HEIGHT-51)
		:setTag(LogonScene.BT_EXIT)
		--	:addTo(self._backLayer)
		:addTouchEventListener(btcallback)
	end
	
	local localver = cc.UserDefault:getInstance():getIntegerForKey(EXTRA_CMD_KEY, 1)
	self._txtTips = cc.Label:createWithTTF("当前版本:" .. localver.."."..appdf.BASE_C_RESVERSION, "fonts/round_body.ttf", 24)
	:setTextColor(cc.c4b(255,250,95,255))
	:setAnchorPoint(cc.p(1,0))
	-- :setVisible(false)
	:enableOutline(cc.c4b(0,0,0,255), 1)
	:move(yl.WIDTH-50,0)
	:addTo(self._topLayer)
	
	--读取配置
	GlobalUserItem.LoadData()
	
	--背景音乐
	ExternalFun.playPlazzBackgroudAudio()
	
	--创建登录界面
	self._logonView = LogonView:create(self:getApp()._serverConfig,self)
	:move(0,0)
	:addTo(self._backLayer,10)
	
	self._logonView:showLoninViewBtn(false)
	
	-- ExternalFun.removeSameSearPath()
	local localver = cc.UserDefault:getInstance():getIntegerForKey("extra_command_version", 1)

	self._txtTips:setString("当前版本:" .. localver.."."..appdf.BASE_C_RESVERSION.."."
	..appdf.channelId..(appdf.isTest and "-test" or ""))
	if device.platform ~= "windows" then
		setbackgroundcallback(function (bEnter)
			if type(self.onBackgroundCallBack) == "function" then
				self:onBackgroundCallBack(bEnter)
			end
		end)
	end

	self:initHttpUrl()
	
	self:initSocketEvent()
	self:initGlobalUserItemConfig()

	xpcall(function( ... )
		local tbArmaturename ={"Armature/plazz/denglujiemian/denglujiemian.ExportJson"}
		ExternalFun.addArmatureCache(tbArmaturename)
		ExternalFun.addLogonLoadingArm( self._backLayer)
	end,function( ... )
		showToast(self,"logon denglujiemian failed",1)
	end)
end

function LogonScene:initGlobalUserItemConfig()
	if appdf.isTest then
		GlobalUserItem.HTTP_API = config_path[4]
	else
		GlobalUserItem.HTTP_API = self:getApp()._serverConfig.http_api or config_path[4]
	end
	--当前大厅版本
	GlobalUserItem.curClientVer = 	self:getApp()._serverConfig.version
end

function LogonScene:resetView( ... )
	--创建登录界面
	if not tolua.isnull(self._logonView) then
		self._logonView:removeSelf()
	end
	
	self._logonView = LogonView:create(self:getApp()._serverConfig,self)
	:move(0,0)
	:addTo(self._backLayer,10)
	ExternalFun.addLogonLoadingArm( self._backLayer )
end

--按钮事件
function LogonScene:onButtonClickedEvent(tag,ref)
	--退出按钮
	ExternalFun.playClickEffect( )
	if tag == LogonScene.BT_EXIT then

		if self:getChildByTag(LogonScene.DG_QUERYEXIT) then
			return
		end
		QueryExit:create("确认退出游戏吗？", function (ok)
			if ok == true then
				os.exit(0)
			end
		end)
		:setTag(LogonScene.DG_QUERYEXIT)
		:addTo(self)
		
	end
end


--登录大厅
function LogonScene:onLogon(szAccount,szPassword,bSave,bAuto)
	--输入检测
	if szAccount == nil or szPassword == nil  then
		return
	end
	local len = ExternalFun.stringLen(szAccount)--#szAccount

	if len < 6 or len > 11 then
		showToast(self,"游戏帐号必须为6~11个字符，请重新输入!",2,cc.c4b(250,0,0,255));
		return
	end
	
	len = ExternalFun.stringLen(szPassword)--#szPassword
	if len<6 then
		showToast(self,"密码必须大于6个字符，请重新输入！",2,cc.c4b(250,0,0,255));
		return
	end
	
	--参数记录
	self._szAccount = szAccount
	self._szPassword = szPassword
	self._bAuto = bAuto
	self._bSave = bSave

	
	--调用登录
	self:showPopWait()
	self._Operate = 0
	-- appdf.clientSocket:onCloseSocket()
	if appdf.clientSocket:isConnected() then
		appdf.clientSocket:sendLogon(szAccount,szPassword)
	else
		appdf.clientSocket:startConnectServer()
	end
	-- appdf.clientSocket:sendLogon(szAccount,szPassword)
end


--游客登录
function LogonScene:onVisitor()
    if self then 
        self:getApp():enterSceneEx(appdf.CLIENT_SRC.."plaza.views.ClientScene","FADE",0.5)
		return
	end

	--调用登录
	self._szAccount = "guest"
	self._szPassword = nil
	self:showPopWait()
	-- appdf.clientSocket:onCloseSocket()s
	if appdf.clientSocket:isConnected() == qxnetlib.socket_state_connect_sucess then
		appdf.clientSocket:sendVisitor()
	else
		appdf.clientSocket:startConnectServer()
	end
	-- appdf.clientSocket:sendVisitor()
end


--登录注册回调
function LogonScene:onLogonCallBack(wMsgID,pData)
	print("onLogonCallBack>>>>",wMsgID)
	if wMsgID == protocol.SM_LOGIN_ACK then 
		--本地保存
		if pData.result ==1 then
			if GlobalUserItem.bNoAutoLogon then
				self._logonView:savePwdAndAount()
				GlobalUserItem.onSaveAccountConfig()
			end
			-- appdf.channelId = pData.channelid
		else
			GlobalUserItem.bNoAutoLogon = false
			print("SM_LOGIN_ACK>>>>",appdf.isPad )
				self:dismissPopWait()
				self._logonView:showLoninViewBtn(true)
				-- showToast(self._topLayer,pData.msg or "登录失败",1,cc.c4b(250,0,0,255));
				self.queryLayer = QueryExit:create(pData.msg or "登录失败", function (bReTry)
				end)
				:setCanTouchOutside(false)
				:addTo(self,yl.MAX_INT)

		end
	-- elseif wMsgID == protocol.SXM_SCROLLNOTICE then   --获取滚动公告

	-- 	yl.brocastData = pData
		-- LogonScene:onLogonCallBack(wMsgID,pData)
	
	elseif wMsgID == protocol.SM_PLAYERINFOEX  and not pData.subid  then
			GlobalUserItem.TodayAlmsCount = pData.todayalmscount or 2  --今天领取了多少次	
			if  device.platform ~= "windows" then
				buglySetUserId(GlobalUserItem.dwUserID)
			end
			-- self:updateInfomation()
	elseif wMsgID == protocol.SM_CHANNELCONFIG then --渠道配置  是否显示游戏公告(SM_GAMENOTICE,)、体现是否需要验证码
		GlobalUserItem.channelconfig = pData   --exchangesms     gamenotice  alimslimit=救济金条件 almsnum=救济金次数   almscount= 救济金数量  reggold=注册送的金额
		local _Layer = self:getChildByTag(yl.SCENE_NOTICE)
		if _Layer then
			_Layer:setreggold()
		end

	elseif wMsgID == protocol.SXM_SCROLLNOTICE then   --获取滚动公告
		local list = pData.list or {}

	elseif wMsgID == protocol.SM_GAMENOTICE then   --获取游戏滚动公告
		local noticedata = cjson.decode(pData.msg)
		
	elseif wMsgID == protocol.SM_GAMELIST then 
		self:getApp():enterSceneEx(appdf.CLIENT_SRC.."plaza.views.ClientScene")
	elseif wMsgID == protocol.SXM_EXCHANGESETTING then --兑换配置
		showToast(self,pData.msg or "",2)
		exchangeConfig= pData
	
		GlobalUserItem.exchangeConfig = exchangeConfig
	elseif wMsgID == protocol.SXM_PLAT  then --平台配置 
		if pData and  pData.list then
			GlobalUserItem.URLconfig = pData.list[1]
		end
	elseif wMsgID < 0 then
		self:dismissPopWait()
		message = pData
		if type(message) == "string" and message ~= "" then
			showToast(self._topLayer,message,1,cc.c4b(250,0,0,255));
		end
		if self.queryLayer and not tolua.isnull(self.queryLayer) then
			return
		end
		self.queryLayer = QueryExit:create(message, function (bReTry)
			if bReTry == true then
				ExternalFun.httpNewVersion(self)
				appdf.clientSocket:startConnectServer()
			else
				os.exit(0)
			end
		end)
		:setCanTouchOutside(false)
		:addTo(self)
	else
		dump(pData,"othermsg")
		print("othermsg>>>",wMsgID)
		-- elseif result == 10 then --重复绑定
		-- 	if self._logonView ~= nil and nil ~= self._logonView.refreshBtnList then
		-- 		self._logonView:refreshBtnList()
		-- 	end
	end
end

--显示等待
function LogonScene:showPopWait(delay)
	if not self._popWait  then
		self._popWait = PopWait:create():show(self._topLayer,"请稍候！")
		self:runAction(
		cc.Sequence:create(
		cc.DelayTime:create(delay or 6),
		cc.CallFunc:create(function ()
			self:dismissPopWait()
		end))
		)
	end
end

--关闭等待
function LogonScene:dismissPopWait()
	if self._popWait ~= nil then
		self._popWait:dismiss()
		self._popWait = nil
	end
end

function LogonScene:onBackgroundCallBack(bEnter)
	print("onBackgroundCallBack bEnter",bEnter)
	appdf.clientSocket.lastPingAck = os.time()
	appdf.PostCustomEvent(yl.EVENT_CALL_BACKGROUND,{bEnter = bEnter},self)
	-- if not bEnter then
	-- 	self.backgroundTs = os.time()
	-- 	cc.Director:getInstance():pause()
	-- 	appdf.clientSocket:pause()
	-- 	cc.SimpleAudioEngine:getInstance():pauseMusic()
	-- 	cc.SimpleAudioEngine:getInstance():pauseAllEffects()
	-- elseif self.backgroundTs then
	-- 	self.backgroundTs = nil
	-- 	cc.Director:getInstance():resume()
	-- 	cc.SimpleAudioEngine:getInstance():resumeMusic()
	-- 	cc.SimpleAudioEngine:getInstance():resumeAllEffects()
	-- 	appdf.clientSocket:resume()
	-- 	self:resetView()
	-- end
end

function LogonScene:openlogonview( ... )
	self:dismissPopWait(0)
	if self._logonView then
		self._logonView:showLoninViewBtn(true)
		self._logonView:initloginAccountCsb()
	end
end
------------teset------------

-- function test( ... )
-- 	for i=1,100000 do
-- 		local tb = {msgid=i,subid=1000+i,info="测试。。。。34fwe0fwfvw"..i}
-- 		local encodestr = EnCode(cjson.encode(tb))
-- 		print("encodestr>>>>>>>>>>>",encodestr)
-- 		local decodestr =  DeCode(encodestr)
-- 		print("encodestr>>>>>>>>>>>",decodestr)
-- 	end
-- end

return LogonScene